import tkinter as tk
from tab_header import *
from tab_grid import *
from tkinter import *
from tkinter import simpledialog
from tools import *
from sys_input_box import *
from sys_sqlite3 import *

"""
只能选中一行

"""
class MainQuery():
    def __init__(self, def_col):
        self.def_col = def_col
        self.tools   = Tools()
        self.sys_sqlite   = SysSqlite()
        self.main()

    def main(self):
        self.window = tk.Tk()
        self.window.title("查询")
        self.window.geometry("1000x560")
        # window.attributes('-fullscreen', True)  #全屏
        # window.wm_state('zoomed') #最大化
        self.window.resizable(True, True)
        self.window.bind("<Configure>", self.on_window_configure)  # 绑定窗口大小改变事件
        self.window.bind("<Visibility>", self.on_window_configure) 
        self.window.bind("<Alt-q>", self.on_window_alt_key_q)
        self.window.bind("<Alt-c>", self.on_window_alt_key_c)
        # self.window.bind("<Alt_R-q>", self.on_window_alt_key_q) 

        # 查询条件
        self.frameWhere = Frame(self.window, bg='blue')
        self.frameWhere.place(x=5, y=5, width=1000, height=30, bordermode='inside')

        # 搜索
        self.frameSearch = Frame(self.window, bg='green')
        self.frameSearch.place(x=5, y=35, width=1000, height=30, bordermode='inside')

        self.stat_str = StringVar()
        search_lbl  = Label(self.frameSearch, width=20, height=1, anchor='w', border=0, textvariable = self.stat_str)
        search_lbl.pack(side='left')

        search_button = Button(self.frameSearch, text="搜索", width=5, height=1, command=self.search_str)
        search_button.pack(side='right')
        search_button = Button(self.frameSearch, text="统计", width=5, height=1, command=self.tab_stat)
        search_button.pack(side='right')
        search_button = Button(self.frameSearch, text="删除选中行", width=10, height=1, command=self.tab_delete2)
        search_button.pack(side='right')
        search_button = Button(self.frameSearch, text="删除指定行", width=10, height=1, command=self.tab_delete)
        search_button.pack(side='right')

        self.search_entry = Entry(self.frameSearch, width=20)
        self.search_entry.pack(side='right', padx=10 )


        #使用 TabHeader 组件实现表头
        self.frameHeader = Frame(self.window, bg='#666')
        self.frameHeader.place(x=5, y=65, width=1000, height=30, bordermode='inside')
        self.th = TabHeader(self.frameHeader, self.def_col, self.onTabHeaderClick)

        # 结果数据
        self.frameData = Frame(self.window, bg='red')
        self.frameData.place(x=5, y=95, width=1000, height=300, bordermode='inside')
        self.tg = TabGrid(self.frameData, self.def_col)

        #右侧按钮 , command =  lambda event: onButonClick('query')
        self.frameRight = Frame(self.window)
        self.frameRight.place(x=1, y=5, width=100, height=300, bordermode='inside')

        btn = Button(self.frameRight, text ="查询(Q)", width=10, height=1, highlightcolor='#333', command = lambda : self.onButonClick('query'))
        btn.pack(side='top', anchor='center', padx=1, pady=1)
        btn = Button(self.frameRight, text ="关闭(C)", width=10, height=1, highlightcolor='#333', command = lambda : self.onButonClick('close'))
        btn.pack(side='top', anchor='center', padx=1, pady=10)

        self.window.mainloop()
        # self.window_adjust(screen_width, screen_height)

    def onTabHeaderClick(self, order_exp):
        print("onTabHeaderClick", order_exp)

    def onButonClick(self, exp):
        print("onButonClick", exp)
        if exp == 'close':
            self.window.destroy()
        if exp == 'query':
            print("onButonClick get_char_width", self.th.get_char_width())
            # self.tg.demo_data(self.th.get_char_width())
            ret = self.sys_sqlite.query('select * from page limit 100')
            self.tg.set_data(ret, self.th.get_char_width())

    def on_window_configure(self, event):
        # label_width = label.winfo_width()
        # print(f"更新后的Label宽度是: {label_width} 像素")
        # width = event.width
        # height = event.height
        # print("on_window_configure",width,height)
        self.window_adjust()


    # 键盘事件
    def on_window_alt_key_q(self, event):
        print("on_window_alt_key_q:")
        self.tg.create_tab(self.th.get_char_width())
        
    def on_window_alt_key_c(self, event):
        print("on_window_alt_key_c:")
        self.window.destroy()

    # 搜索
    def search_str(self):
        ss = self.search_entry.get()
        if len(ss) == 0:
            # messagebox.showwarning("警告", "请输入搜索内容！")
            self.tools.msg('请输入搜索内容！', 'warning')
            return
        
        # ret = self.tools.msg('请输入搜索内容！', 'yesno')
        # self.tools.msg('hi')
        print("search_str", ss, self.tg.search(ss))

    def tab_stat(self):
        _count = self.tg.get_count()
        selected_count = self.tg.get_selected_count()
        print(f"tab_stat,行数{_count}：选中{selected_count}行")
        self.stat_str.set(f"行数{_count},选中{selected_count}行")

        selected_num = self.tg.get_selected_num()
        print("selected_num", selected_num)
        selected_id = self.tg.get_selected_id()
        print("selected_id", selected_id)
        get_cell = self.tg.get_cell(5, 3)
        print("get_cell", get_cell)

    # 删除指定行
    def tab_delete(self):
        SysInputBox(self.window, self.tab_delete_do, '请输入行号:', 'number', True)

    def tab_delete_do(self, content):
        print("tab_delete_do", content)
        if content == '': return
        if content.isdigit() == False: return
        self.tg.delete(int(content))
    # 删除选中行
    def tab_delete2(self):
        self.tg.delete2()

    # 根据窗口大小调整内部组件的位置和大小
    def window_adjust(self):
        # 获取宽度和高度
        # screen_width = self.window.winfo_screenwidth()
        # screen_height = self.window.winfo_screenheight()
        win_width   = self.window.winfo_width()
        win_height  = self.window.winfo_height()
        
        # print(f"screen:{win_width},{win_height}")
        _right  = 100
        _left   = win_width - _right
        if _left < 1:
            return
        
        self.frameWhere.place(x=5, y=5, width=_left, height=30) 
        self.frameSearch.place(x=5, y=35, width=_left-4, height=30) 
        self.frameHeader.place(x=5, y=65, width=_left, height=30) 
        self.frameData.place(x=5, y=95, width=_left-4, height=(win_height - 99)) 
        self.frameRight.place(x=_left, y=5, height=win_height)
                      
    def do_query():
        pass

if __name__ == "__main__":
    """
    format:格式
    trans:数据转换指令
    特殊字段名：_row_num_,表示行号
    """
    def_col = [
        {'field': 'page_id',        'caption': '页ID',      'width':10,   'align':'center', 'format':'', 'order':'asc', 'trans':''},
        {'field': 'author_uid',     'caption': '作者ID',    'width':20,   'align':'n',      'format':'',  'order':''},
        {'field': 'author_username','caption': '作者姓名',  'width':12,   'align':'n',      'format':'',  'order':''},
        {'field': 'page_title',     'caption': '标题',      'width':28,    'align':'center',     'format':'',  'order':'_not_'},
        {'field': 'addtime',        'caption': '添加时间',  'width':12,   'align':'w',      'format':'',  'order':''},
        {'field': 'is_del',         'caption': '删除',      'width':20,   'align':'center', 'format':'',   'order':''},
        {'field': 'ext_info',       'caption': '扩展信息',  'width':15,   'align':'w', 'format':'',  'order':''},
    ]
    def_rep = {
        'id_field':  'rowid'
    }
    mq = MainQuery(def_col)
    